package com.czy.owner.ui.packagecardproject;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.adapter.StorePackageDetailAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyServicePackageItemList;
import com.czy.owner.entity.PuchPackageCardDetailModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.FullyLinearLayoutManager;
import com.czy.owner.widget.MyRecyclerView;
import com.czy.owner.widget.RoundImageView;
import com.czy.owner.widget.UniversalDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/12/15 0015.
 * 门店套餐详细
 */
public class PushPackageCardDetailActivity extends BaseActivity /*implements MyScrollView.ScrollViewLine*/ {
    //    @ViewInject(R.id.myscrollview)
//    private MyScrollView myScrollView;
//    @ViewInject(R.id.line_headview)
//    private LinearLayout lineHeadView;
    @BindView(R.id.relative_push)
    RelativeLayout relativePush;
    @BindView(R.id.img_user_head_portrait)
    RoundImageView imgPortrait;
    @BindView(R.id.tv_jishi_name)
    TextView tvJishiName;

    @BindView(R.id.img_package_card_bg)
    ImageView imgPackageCardBg;
    @BindView(R.id.tv_package_card_name)
    TextView tvPackageCardName;
    @BindView(R.id.tv_now_price)
    TextView tvNowPrice;
    @BindView(R.id.tv_used_time)
    TextView tvUserTime;
    //2018-2-27wangyang新增
    @BindView(R.id.ll_package_price)
    LinearLayout llPackagePrice;
    @BindView(R.id.tv_old_price)
    TextView tvOldPrice;
    @BindView(R.id.tv_package_note)
    TextView tvPackageNote;

    @BindView(R.id.tv_bottom_old_price)
    TextView tvBottomOldPrice;
    @BindView(R.id.tv_bottom_now_price)
    TextView tvBottomNowPrice;
    //商品
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.rv_package_detail_goods)
    MyRecyclerView rvPackageDetailGoods;
    @BindView(R.id.tv_package_goods_head_title)
    TextView tvPackageGoodsHeadTitle;
    @BindView(R.id.tv_package_goods_head_money)
    TextView tvPackageGoodsHeadMoney;
    //服务
    @BindView(R.id.ll_service)
    LinearLayout llService;
    @BindView(R.id.rv_package_detail_service)
    MyRecyclerView rvPackageDetailService;
    @BindView(R.id.tv_package_service_head_title)
    TextView tvPackageServiceHeadTitle;
    @BindView(R.id.tv_package_service_head_money)
    TextView tvPackageServiceHeadMoney;
    @BindView(R.id.tv_give_amount)
    TextView tvGiveAmount;



    private int servicePackageId = 0;
    private int pushPackageId = 0;
    private int storeId;

    private double priceGood = 0.00;
    private double priceService = 0.00;
    private double totalPrice = 0.00;
    private String callPhone;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_package_card_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
//        setTitleLayout(lineHeadView);
//        lineHeadView.setFocusable(true);
//        lineHeadView.setFocusableInTouchMode(true);
//        lineHeadView.requestFocus();
//        lineHeadView.getBackground().setAlpha(0);//开始是透明的
//        myScrollView.setScrollViewLine(this);
        getToolbarTitle().setText(R.string.my_package_card_detail);
        tvOldPrice.setVisibility(View.GONE);
        tvNowPrice.setVisibility(View.GONE);
        relativePush.setVisibility(View.VISIBLE);
        servicePackageId = getIntent().getIntExtra("servicePackageId", 0);
        pushPackageId = getIntent().getIntExtra("pushPackageId", 0);
        RxBus.getDefault().register(this);
        getData();
    }

    @Override
    protected void updateViews() {

    }


    private void getData() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_PAC_PUSHINF;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PushPackageCardDetailActivity.this).getSession());
        params.addBodyParameter("pushPackageId", pushPackageId + "");
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(PushPackageCardDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                if (flag) {
                    String data = PhoneUtils.checkResponseFlag(PushPackageCardDetailActivity.this, result);
                    Gson gson = new GsonBuilder().create();
                    PuchPackageCardDetailModel model = gson.fromJson(data, PuchPackageCardDetailModel.class);
                    GlideUtils.loadImage(PushPackageCardDetailActivity.this, model.getUserLogo(), imgPortrait, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                        @Override
                        public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                        }

                        @Override
                        public void onLoadingError(String source, Exception e) {

                        }
                    }, R.mipmap.default_icon, R.mipmap.default_icon);
                    tvJishiName.setText(model.getEmployeesName());
                    storeId = model.getStoreId();
                    totalPrice = model.getPrice();
                    callPhone = model.getPhone();


                    if (TextUtils.isEmpty(model.getLogo()) || model.getLogo().equals(" ")) {
                        imgPackageCardBg.setVisibility(View.GONE);
                    } else {
                        GlideUtils.loadImage(PushPackageCardDetailActivity.this, model.getLogo(), imgPackageCardBg, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                            @Override
                            public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                            }

                            @Override
                            public void onLoadingError(String source, Exception e) {

                            }
                        }, R.mipmap.default_icon, R.mipmap.default_icon);
                    }
                    if (model.getGiveAmount() > 0) {
                        tvGiveAmount.setVisibility(View.VISIBLE);
                        tvGiveAmount.setText("¥" + DecimalUtil.formatNum(model.getGiveAmount() + ""));

                    } else {
                        tvGiveAmount.setVisibility(View.GONE);

                    }
                    tvPackageCardName.setText(model.getPackageName());
                    //2018-2-27 wangyang 修改
                    tvBottomOldPrice.setText("原价￥" + String.format("%.2f", model.getOriginalPrice()));
                    tvBottomOldPrice.setPaintFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
                    tvBottomNowPrice.setText("现价￥" + String.format("%.2f", model.getPrice()));

                    if (model.getGiveAmount() > 0) {
                        llPackagePrice.setVisibility(View.VISIBLE);
                        tvGiveAmount.setVisibility(View.VISIBLE);
                        tvGiveAmount.setText("赠送余额: ¥" + DecimalUtil.formatNum(model.getGiveAmount() + ""));

                    } else {
                        llPackagePrice.setVisibility(View.GONE);
                        tvGiveAmount.setVisibility(View.INVISIBLE);

                    }
                    if(!TextUtils.isEmpty(model.getNote())){
                        tvPackageNote.setVisibility(View.VISIBLE);
                        tvPackageNote.setText(model.getNote());
                    }else {
                        tvPackageNote.setVisibility(View.GONE);
                    }

                    int validityType = model.getValidityType();//0>>>永久有效;1>>>固定时长;2>>>固定时间
                    int fixTimeType = model.getFixTimeType();//0>>>>>月;1>>>>年

                    if (validityType == 0) {
                        tvUserTime.setText("有效期: 永久有效");
                    } else if (validityType == 1) {
                        if (fixTimeType == 0) {
                            tvUserTime.setText("有效期: " + model.getFixTimeValue() + "个月");
                        } else if (fixTimeType == 1) {
                            tvUserTime.setText("有效期: " + model.getFixTimeValue() + "年");
                        }
                    } else if (validityType == 2) {
                        tvUserTime.setText("有效期: " + TimeUtils.formatTimeDifference4(model.getStartTime()) + "至" + TimeUtils.formatTimeDifference4(model.getEndTime()));
                    }

                    List<MyServicePackageItemList> goodsList = new ArrayList<>();
                    List<MyServicePackageItemList> serviceList = new ArrayList<>();

                    if (model.getServicePackageItemList().size() > 0) {
                        for (int i = 0; i < model.getServicePackageItemList().size(); i++) {
                            String itemType = model.getServicePackageItemList().get(i).getItemType();
                            String itemName = model.getServicePackageItemList().get(i).getItemName();
                            double price = model.getServicePackageItemList().get(i).getPrice();
                            int count = model.getServicePackageItemList().get(i).getCount();
                            String logo = model.getServicePackageItemList().get(i).getLogo();
                            String specValue = model.getServicePackageItemList().get(i).getSpecValue();
                            boolean unlimitedCount = model.getServicePackageItemList().get(i).isUnlimitedCount();
                            if (itemType.equals("goods")) {
                                goodsList.add(new MyServicePackageItemList(itemName, price, count, logo, specValue,unlimitedCount));
                            } else if (itemType.equals("service")) {
                                serviceList.add(new MyServicePackageItemList(itemName, price, count, logo, specValue,unlimitedCount));
                            }

                        }
                    }

                    if (goodsList != null && goodsList.size() > 0) {
                        FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(PushPackageCardDetailActivity.this);
                        rvPackageDetailGoods.setLayoutManager(layoutManager);
                        rvPackageDetailGoods.addItemDecoration(new RecycleViewDivider(PushPackageCardDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
                        rvPackageDetailGoods.setAdapter(new StorePackageDetailAdapter(PushPackageCardDetailActivity.this, goodsList, false));
                        for (int i = 0; i < goodsList.size(); i++) {
                            priceGood = goodsList.get(i).getPrice() * goodsList.get(i).getCount() + priceGood;
                        }
                        tvPackageGoodsHeadTitle.setText("商品项目");
//                        tvPackageGoodsHeadMoney.setText("小计: ￥" + String.format("%.2f", priceGood));
                        tvPackageGoodsHeadMoney.setText("");
                    } else {
                        llGoods.setVisibility(View.GONE);
                    }

                    MyLog.e("yang", "serviceList==" + serviceList.size());

                    if (serviceList != null && serviceList.size() > 0) {
                        FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(PushPackageCardDetailActivity.this);
                        rvPackageDetailService.setLayoutManager(layoutManager);
                        rvPackageDetailService.addItemDecoration(new RecycleViewDivider(PushPackageCardDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
                        rvPackageDetailService.setAdapter(new StorePackageDetailAdapter(PushPackageCardDetailActivity.this, serviceList, false));

                        for (int i = 0; i < serviceList.size(); i++) {
                            priceService = serviceList.get(i).getPrice() * serviceList.get(i).getCount() + priceService;

                        }
                        tvPackageServiceHeadTitle.setText("服务项目");
//                        tvPackageServiceHeadMoney.setText("小计: ￥" + String.format("%.2f", priceService));
                        tvPackageServiceHeadMoney.setText("");
                    } else {
                        llService.setVisibility(View.GONE);
                    }


                } else {
                    PhoneUtils.ShowToastMessage(PushPackageCardDetailActivity.this, exp);
                    finish();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });

    }


    @OnClick(R.id.btn_store_package)
    public void btnStorePackage(View view) {
        if (totalPrice == 0.00) {
            helpDialog("温馨提示", "是否进行购买套餐", "确定", "取消");
        } else {
            Intent ti = new Intent(PushPackageCardDetailActivity.this, BuyStorePackageActivity.class);
            ti.putExtra("totalPrice", totalPrice);
            ti.putExtra("servicePackageId", servicePackageId + "");
            ti.putExtra("pushPackageId", pushPackageId);
            ti.putExtra("storeId", storeId);
            ti.putExtra("numbers", "1");
            startActivity(ti);
        }


    }

    @Subscribe(code = Constants.BUY_PACKAGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventBuyPackage(CommonEvent bugPackageEvent) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);

    }


    protected void setTitleLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(PushPackageCardDetailActivity.this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);

        }
    }

    @OnClick(R.id.img_push_phone)
    public void pushCallPhone(View view) {
        phoneCall("确定", callPhone);
    }

    private void phoneCall(String sure, final String phone) {
        new UniversalDialog(PushPackageCardDetailActivity.this).builder().setTitle(phone)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ((Build.VERSION.SDK_INT >= 23)) {
                            onClickCallPhone(phone);
                        } else {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_CALL);
                            intent.setData(Uri.parse("tel:" + phone));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                    }
                }).show();
    }

    public void onClickCallPhone(final String phone) {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.CALL_PHONE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phone));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(PushPackageCardDetailActivity.this, permissions.toString() + "权限拒绝");

                    }
                });

    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    private void payDepositAmount() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_BUYPACKAGE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PushPackageCardDetailActivity.this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("useStoreBalance", "true");
        params.addBodyParameter("servicePackageId", servicePackageId + "");
        params.addBodyParameter("pushPackageId", pushPackageId + "");
        params.addBodyParameter("numbers", "1");
        MyLog.e("yang", "params==" + params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "套餐付款onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(PushPackageCardDetailActivity.this, result);
                if (data != null) {
                    if (data.equals("")) {
                        RxBus.getDefault().post(Constants.BUY_PACKAGE_SUCCESS_CODE, new CommonEvent("购买套餐"));
                        PhoneUtils.ShowToastMessage(PushPackageCardDetailActivity.this, "购买该套餐成功");
                    }

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "套餐付款onError==" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


//    @Override
//    public void onScrollChanged(int l, int t, int oldl, int oldt) {
//        if (oldt < 10) {
//            lineHeadView.getBackground().setAlpha(0);
//        } else if (oldt < 40 && oldt > 10) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 8));
//        } else if (oldt < 70 && oldt > 40) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 7));
//        } else if (oldt < 100 && oldt > 70) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 6));
//        } else if (oldt < 130 && oldt > 100) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 5));
//        } else if (oldt < 150 && oldt > 130) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 4));
//        } else if (oldt < 180 && oldt > 150) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 3));
//        } else if (oldt < 200 && oldt > 180) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 2));
//        } else if (oldt >= 200) {
//            lineHeadView.getBackground().setAlpha(255);
//        }
//    }

    private void helpDialog(String title, String msg, String sure, String cancle) {
        new UniversalDialog(PushPackageCardDetailActivity.this).builder()
                .setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        payDepositAmount();
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
